package com.thti.mecool.client.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.thti.mecool.client.adapter.WorkMemoShowAdapter;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.command.send.work.WorkmemoSend;
import com.thti.mecool.client.model.biz.WorkmemoBizImpl;
import com.thti.mecool.client.protocol.work.MemoDto;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.MyListView;
import com.thti.mecool.client.widget.MyListView.OnRefreshListener;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

public class WorkMemoActivity extends BaseActivity {
	MyListView MemoListView;
	List<MemoDto> MemoList;
	int curItem;
	String curItemCode;
	int stat = 0;
	ProgressDialogWidget pd;
	boolean echo = false;
	int curpage = 1;
	boolean isHashNext = false;
	WorkmemoBizImpl workmemoBizImpl;
	WorkMemoShowAdapter workMemoShowAdapter;
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			System.out.println("runnable！！！！！！！！！！！！！！！！！！！！！！1");
			switch (stat) {
			case 0:
				if (getDataFlag(HandlerConstant.WorkMemosCommand)) {
					if (pd.isShowing()) {
						pd.dismiss("数据获取成功！");
					}
					isHashNext = true;
					handler.removeCallbacks(runnable);
					removeDataFlag(HandlerConstant.WorkMemosCommand);
					MemoListView.onRefreshComplete();
					if (curpage == 1)
						MemoList.clear();
					MemoList.addAll(workmemoBizImpl.findAll(curpage));
					workMemoShowAdapter.notifyDataSetChanged();
					MemoListView.onRefreshComplete();
				} else if (getDataFlag(HandlerConstant.WorkMemosHasNextCommand)) {
					if (pd.isShowing()) {
						pd.dismiss("数据获取成功！");
					}
					handler.removeCallbacks(runnable);
					removeDataFlag(HandlerConstant.WorkMemosHasNextCommand);
					if (curpage == 1)
						MemoList.clear();
					MemoList.addAll(workmemoBizImpl.findAll(curpage));
					workMemoShowAdapter.notifyDataSetChanged();
					MemoListView.onRefreshComplete();
				} else {
					if (getDataFlag(HandlerConstant.CommandFail)) {
						if (pd.isShowing()) {
							if (getCurrentMesg() != null)
								if (getCurrentMesg().getContent() != null)
									pd.dismiss(getCurrentMesg().getContent());
								else
									pd.dismiss("数据获取异常！");
						}
						isHashNext = true;
						curpage--;
						removeDataFlag(HandlerConstant.CommandFail);
						handler.removeCallbacks(runnable);
					} else
						handler.postDelayed(runnable, 1000);
				}
				break;
			case 1:
				if (getCurrentMesg() != null) {
					pd.dismiss("成功！");
					handler.removeCallbacks(runnable);
					handler.sendEmptyMessage(5);
				} else {
					handler.postDelayed(runnable, 500);
				}
				break;
			}
		}
	};

	Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				post(runnable);
				break;
			case 2:
				WorkmemoSend.deleteWorkmemo(MemoList.get(curItem).getMemoId(),
						getCurrentUser().getLoginName());
				stat = 1;
				if (pd != null) {
					if (!pd.isShowing()) {
						pd.show();
					}
				}
				post(runnable);
				break;
			case 5:
				/**
				 * 删除成功
				 */
				MemoList.remove(curItem);
				ArrayList<MemoDto> temp = new ArrayList<MemoDto>();
				temp.addAll(MemoList);
				MemoList.clear();
				MemoList.addAll(temp);
				workMemoShowAdapter.notifyDataSetChanged();
				break;
			case HandlerConstant.WORKMEMOLISTREFRESH:
				workMemoShowAdapter.notifyDataSetChanged();
				break;
			}
		};
	};

	OnItemClickListener onItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			curItem = arg2;
			Intent intent = new Intent(WorkMemoActivity.this,
					WorkMemoContentDetailActivity.class);
			intent.putExtra("item", MemoList.get(arg2));
			intent.putExtra("curItemCode", MemoList.get(curItem)
					.getChannelCode());
			intent.putExtra("editcommId", MemoList.get(curItem).getMemoId());
			startActivity(intent);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.noTitle();
		setContentView(R.layout.mecool_workmemo);
		Cache.add(this);
		initToolbar();
		workmemoBizImpl = new WorkmemoBizImpl(this);
		MemoListView = (MyListView) findViewById(R.id.mecool_workmemo_listview);
		MemoList = new ArrayList<MemoDto>();
		MemoList.addAll(workmemoBizImpl.findAll(1));
		workMemoShowAdapter = new WorkMemoShowAdapter(MemoList, this);
		MemoListView.setAdapter(workMemoShowAdapter);
		MemoListView.setOnItemClickListener(onItemClickListener);
		pd = new ProgressDialogWidget(this, false);
		/**
		 * 删除备忘
		 */
		MemoListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				curItem = arg2;
				dialog();
				return false;
			}
		});
		MemoListView.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if (isHashNext) {
					MemoListView.onRefreshComplete();
					Util.sendToast(WorkMemoActivity.this, "已经到底部了");
				} else {
					curpage++;
					System.out.println();
					WorkmemoSend.searchWorkmemo(
							getCurrentUser().getLoginName(), curpage, 10);
					handler.post(runnable);
					System.out.println("post了了了了了！");
				}
			}
		});

		if (MemoList != null && MemoList.size() > 0)
			stat = 0;
//		if (!getSharedPreferences("Setting", 0)
//				.getBoolean("AutoRefresh", false)) {
			WorkmemoSend.searchWorkmemo(getCurrentUser().getLoginName(), 1, 10);
			handler.sendEmptyMessage(1);
			pd.setDismissTime(60);
			if (!pd.isShowing()) {
				pd.show();
//			}
		}
	}

	public void initToolbar() {
		Toolbar toolbar = new Toolbar(this);
		toolbar.setToolbarCentreText("工作备忘");
		Toolbar.left_btn.setOnClickListener(ToolbarBtnListener);
		Toolbar.right_btn.setOnClickListener(ToolbarBtnListener);
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
		Toolbar.right_btn.setImageResource(R.drawable.mecool_add_work_memo_add);
	}

	private OnClickListener ToolbarBtnListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_toolbar_rightbtn:
				Intent intent = new Intent(WorkMemoActivity.this,
						AddWorkMemoActivity.class);
				startActivityForResult(intent, 9);
				break;
			default:
				finish();
				break;
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (!echo) {
		} else {
			MemoList.clear();
			MemoList.addAll(workmemoBizImpl.findAll(0));
			MemoList.addAll(workmemoBizImpl.findAll(1));
			workMemoShowAdapter.notifyDataSetChanged();
		}
	};

	@Override
	public void dialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定要删除吗？").setTitle("提示");
		builder.setPositiveButton("确定", dialogOnClickListener)
				.setNegativeButton("取消", dialogOnClickListener);
		builder.create().show();
	}

	DialogInterface.OnClickListener dialogOnClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case -1:
				workmemoBizImpl.delete(MemoList.get(curItem).getMemoId());
				handler.sendEmptyMessage(2);
				break;
			default:
				dialog.dismiss();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("resultCode :    " + resultCode);
		if (resultCode == 10) {
			echo = true;
		} else {
			echo = false;
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		if (getCurrentMesg() != null) {
			setCurrentMesg(null);
		}
	};

	@Override
	protected void onDestroy() {
		if (getDataFlag(HandlerConstant.WorkMemosCommand)) {
			removeDataFlag(HandlerConstant.WorkMemosCommand);
		}
		super.onDestroy();
	};

}
